<?php

namespace App\Repositories\Eloquent\Act;

use Illuminate\Container\Container as App;
use Illuminate\Support\Arr;
use App\Repositories\Eloquent\Repository;
use DB;

class QuestionRepository extends Repository
{

    /**
     * @param App
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Act\Question';
    }

    /**
     * 按题型过滤
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $result = $this->model
            ->with('options')
            ->orderBy('id', 'asc');

        return $result;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($request, $tid)
    {
        switch ($request->type) {
            case 1:
                return self::storeSelect($request, $tid);
                break;
            case 2:
                return self::storeBlank($request, $tid);
                break;
            default:
                break;
        }
    }

    /**
     * 保存选择题型
     *
     * @param [type] $request
     * @param [type] $tid
     * @return void
     */
    private function storeSelect($request, $tid)
    {
        $correct = $request->correct;

        $data = array();

        DB::beginTransaction();

        try {
            /**题目 */
            $question = $this->create([
                'title'      => $request->title,
                'type'       => $request->type,
                'topic_id'   => $tid,
            ]);
            /**题目选项 */
            if (!!$question) {
                for ($i = 0; $i <= 3; $i++) {
                    $data[] = [
                        'question_id' => $question->id,
                        'content' => $request->content[$i],
                        'isCorrect' => $correct[$i]
                    ];
                }
                DB::table('act_options')->insert($data);
            }

            $type = array_count_values($correct);
            $ans = Arr::get($type, '1');
            if ($ans > 1) {
                $question->single = 0;
                $question->update();
            }

            DB::commit();

            return $this->responseSuccess('增加题目成功', $question, route('act.question.index', $tid));
        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500, '增加题目失败');
        }
    }

    /**
     * 保存填空题型
     *
     * @param [type] $request
     * @param [type] $tid
     * @return void
     */
    private function storeBlank($request, $tid)
    {
        DB::beginTransaction();

        try {
            /**题目 */
            $question = $this->create([
                'title'      => $request->title,
                'type'       => $request->type,
                'topic_id'   => $tid,
            ]);

            $option = \App\Models\Act\Option::create([
                'question_id' => $question->id,
                'content' => $request->content,
            ]);

            DB::commit();

            return $this->responseSuccess('增加题目成功', $question, route('act.question.index', $tid));
        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500, '增加题目失败');
        }
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $question = $this->find($id);

        if (!$question)
            return $this->responseFail(404, '题目信息不正确');

        return $question;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function renew($request, $tid, $qid)
    {
        switch ($request->type) {
            case 1:
                return self::updateSelect($request, $tid, $qid);
                break;
            case 2:
                return self::updateBlank($request, $tid, $qid);
                break;
            default:
                break;
        }
    }

    private function updateSelect($request, $tid, $qid)
    {
        $correct = $request->correct;

        $data = array();

        DB::beginTransaction();

        try {
            for ($i = 0; $i <= 3; $i++) {
                $data[] = [
                    'id' => $request->id[$i],
                    'content' => $request->content[$i],
                    'isCorrect' => $correct[$i]
                ];
            }
            $this->updateBatch('bank_act_options', $data);

            $type = array_count_values($correct);
            $ans = Arr::get($type, '1');
            $question = $this->update([
                'title' => $request->title,
                'single' => $ans == 1 ? 1 : 0,
            ], $qid);

            DB::commit();

            return $this->responseSuccess('更新题目成功', $question, route('act.question.index', $tid));
        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500, '更新题目失败');
        }
    }


    private function updateBlank($request, $tid, $qid)
    {
        DB::beginTransaction();

        try {
            $question = $this->update([
                'title' => $request->title,
            ], $qid);

            $option = $this->find($qid)->options->first();
            $option->content = $request->content;
            $option->update();

            DB::commit();

            return $this->responseSuccess('更新题目成功', $question, route('act.question.index', $tid));
        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500, '更新题目失败');
        }
    }

    public function updateBatch($tableName = "", $multipleData = array())
    {

        if ($tableName && !empty($multipleData)) {

            // column or fields to update
            $updateColumn = array_keys($multipleData[0]);
            $referenceColumn = $updateColumn[0]; //e.g id
            unset($updateColumn[0]);
            $whereIn = "";

            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .=  $uColumn . " = CASE ";

                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }
            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" .  rtrim($whereIn, ', ') . ")";

            // Update
            return DB::update(DB::raw($q));
        } else {
            return false;
        }
    }

    /**
     * 正确答案
     *
     * @return void
     */
    public function corrects($request)
    {
        return $this->model->options
            ->where('question_id', $request->question_id)
            ->where('isCorrect', STATUS_NORMAL)
            ->get();
    }
}
